import pygame
import random
import math
import sys
import time

# 初始化pygame
pygame.init()

# 屏幕设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("吸血鬼幸存者风格游戏")

# 颜色定义
BACKGROUND = (20, 20, 40)
PLAYER_COLOR = (0, 200, 255)
ENEMY_COLOR = (200, 50, 50)
XP_COLOR = (50, 200, 50)
TEXT_COLOR = (230, 230, 230)
UI_BG = (30, 30, 60, 180)
UI_BORDER = (80, 120, 180)
BOTTOM_MENU_BG = (25, 25, 50)
BOTTOM_MENU_HIGHLIGHT = (70, 100, 150)

# 字体系统改进 - 使用默认字体确保兼容性
def get_font(size):
    try:
        # 直接指定一个中文字体
        return pygame.font.SysFont("simhei", size)
    except:
        # 回退方案
        return pygame.font.Font(None, size)

# 字体大小定义
font_small = get_font(20)
font_medium = get_font(28)
font_large = get_font(40)
font_title = get_font(48)

# 玩家类
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.radius = 15
        self.speed = 4
        self.health = 100
        self.max_health = 100
        self.level = 1
        self.xp = 0
        self.xp_to_level = 20
        self.weapons = [Weapon("魔法飞弹", 1.0, 5, 200)]
        self.passives = {}
        self.last_damage_time = 0
        self.invulnerable = False
        self.xp_multiplier = 1.5  # 经验值乘数
        
    def move(self, dx, dy):
        # 确保玩家不会移出屏幕
        self.x = max(self.radius, min(WIDTH - self.radius, self.x + dx * self.speed))
        self.y = max(self.radius, min(HEIGHT - self.radius, self.y + dy * self.speed))
    
    def draw(self, screen):
        # 绘制玩家
        pygame.draw.circle(screen, PLAYER_COLOR, (int(self.x), int(self.y)), self.radius)
        pygame.draw.circle(screen, (255, 255, 255), (int(self.x), int(self.y)), self.radius, 2)
        
        # 绘制玩家朝向指示器
        mouse_x, mouse_y = pygame.mouse.get_pos()
        angle = math.atan2(mouse_y - self.y, mouse_x - self.x)
        indicator_x = self.x + math.cos(angle) * (self.radius + 5)
        indicator_y = self.y + math.sin(angle) * (self.radius + 5)
        pygame.draw.circle(screen, (255, 255, 0), (int(indicator_x), int(indicator_y)), 5)
        
        # 绘制血条
        bar_width = 50
        bar_height = 5
        bar_x = self.x - bar_width // 2
        bar_y = self.y - self.radius - 10
        pygame.draw.rect(screen, (100, 0, 0), (bar_x, bar_y, bar_width, bar_height))
        pygame.draw.rect(screen, (0, 200, 0), (bar_x, bar_y, bar_width * (self.health / self.max_health), bar_height))

    def add_xp(self, amount):
        # 应用经验值乘数
        actual_amount = int(amount * self.xp_multiplier)
        self.xp += actual_amount
        
        # 检查升级
        levels_gained = 0
        while self.xp >= self.xp_to_level:
            self.level_up()
            levels_gained += 1
            # 防止无限循环
            if levels_gained > 10: 
                break
                
        return levels_gained > 0
    
    def level_up(self):
        # 修复经验值负数问题
        self.xp = max(0, self.xp - self.xp_to_level)
        self.level += 1
        # 增加升级所需经验
        self.xp_to_level = int(self.xp_to_level * 1.5)
        # 升级时恢复部分生命值
        self.health = min(self.max_health, self.health + 20)
        return True  # 表示需要选择升级
    
    def take_damage(self, amount):
        current_time = time.time()
        if current_time - self.last_damage_time > 0.5:  # 0.5秒无敌时间
            self.health -= amount
            self.last_damage_time = current_time
            return True
        return False

# 敌人类
class Enemy:
    def __init__(self, x, y, enemy_type="normal"):
        self.x = x
        self.y = y
        self.type = enemy_type
        
        if enemy_type == "normal":
            self.radius = 12
            self.speed = 1.5
            self.health = 30
            self.damage = 10
            self.color = (200, 50, 50)
            self.xp_value = 5
        elif enemy_type == "fast":
            self.radius = 8
            self.speed = 3.0
            self.health = 15
            self.damage = 5
            self.color = (220, 100, 50)
            self.xp_value = 3
        elif enemy_type == "tank":
            self.radius = 20
            self.speed = 0.8
            self.health = 100
            self.damage = 20
            self.color = (150, 30, 30)
            self.xp_value = 15
        elif enemy_type == "boss":
            self.radius = 30
            self.speed = 0.5
            self.health = 300
            self.damage = 30
            self.color = (180, 0, 0)
            self.xp_value = 50
    
    def move(self, player_x, player_y):
        dx = player_x - self.x
        dy = player_y - self.y
        dist = max(0.1, math.sqrt(dx*dx + dy*dy))
        self.x += (dx / dist) * self.speed
        self.y += (dy / dist) * self.speed
    
    def draw(self, screen):
        pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
        pygame.draw.circle(screen, (100, 0, 0), (int(self.x), int(self.y)), self.radius, 1)
        
        # 绘制血条
        bar_width = 30 + (self.radius - 12) * 2
        bar_height = 3
        bar_x = self.x - bar_width // 2
        bar_y = self.y - self.radius - 8
        pygame.draw.rect(screen, (50, 0, 0), (bar_x, bar_y, bar_width, bar_height))
        pygame.draw.rect(screen, (200, 0, 0), (bar_x, bar_y, bar_width * (self.health / self.get_max_health()), bar_height))
    
    def get_max_health(self):
        if self.type == "normal":
            return 30
        elif self.type == "fast":
            return 15
        elif self.type == "tank":
            return 100
        elif self.type == "boss":
            return 300
    
    def take_damage(self, amount):
        self.health -= amount
        return self.health <= 0

# 经验值类
class XPOrb:
    def __init__(self, x, y, value=1):
        self.x = x
        self.y = y
        self.radius = 5
        self.value = value
        self.color = XP_COLOR
        self.speed = 2.0
        self.collected = False
        self.creation_time = time.time()
    
    def move_towards_player(self, player_x, player_y):
        dx = player_x - self.x
        dy = player_y - self.y
        dist = max(0.1, math.sqrt(dx*dx + dy*dy))
        
        # 当经验球靠近玩家时加速
        if dist < 100:
            speed = self.speed + (100 - dist) * 0.05
            self.x += (dx / dist) * speed
            self.y += (dy / dist) * speed
    
    def draw(self, screen):
        # 添加脉动效果
        pulse = math.sin(time.time() * 5) * 1.5
        current_radius = max(3, self.radius + pulse)
        
        pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), int(current_radius))
        pygame.draw.circle(screen, (100, 255, 100), (int(self.x), int(self.y)), int(current_radius), 1)

# 武器类
class Weapon:
    def __init__(self, name, cooldown, damage, range):
        self.name = name
        self.cooldown = cooldown
        self.damage = damage
        self.range = range
        self.timer = 0
        self.level = 1
        self.max_level = 8
    
    def update(self, dt, player, enemies):
        self.timer -= dt
        if self.timer <= 0:
            self.timer = self.cooldown
            
            # 寻找范围内的敌人
            target = None
            min_dist = float('inf')
            
            for enemy in enemies:
                dist = math.sqrt((player.x - enemy.x)**2 + (player.y - enemy.y)**2)
                if dist < self.range and dist < min_dist:
                    min_dist = dist
                    target = enemy
            
            if target:
                return Projectile(player.x, player.y, target, self.damage * (1 + (self.level-1)*0.3))
        return None
    
    def upgrade(self):
        if self.level < self.max_level:
            self.level += 1
            self.cooldown *= 0.85
            return True
        return False

# 投射物类
class Projectile:
    def __init__(self, x, y, target, damage):
        self.x = x
        self.y = y
        self.target = target
        self.speed = 8
        self.damage = damage
        self.radius = 4
        self.color = (150, 200, 255)
        self.hit = False
        self.creation_time = time.time()
    
    def update(self):
        if self.hit or not self.target:
            return True
        
        dx = self.target.x - self.x
        dy = self.target.y - self.y
        dist = max(0.1, math.sqrt(dx*dx + dy*dy))
        
        self.x += (dx / dist) * self.speed
        self.y += (dy / dist) * self.speed
        
        # 检查是否击中目标
        if dist < self.target.radius + self.radius:
            self.target.take_damage(self.damage)
            self.hit = True
            return True
        
        # 投射物存活时间过长时消失
        if time.time() - self.creation_time > 5:
            return True
        
        return False
    
    def draw(self, screen):
        # 添加拖尾效果
        pygame.draw.circle(screen, (100, 150, 200, 100), (int(self.x), int(self.y)), self.radius + 2)
        pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
        pygame.draw.circle(screen, (200, 230, 255), (int(self.x), int(self.y)), self.radius, 1)

# 升级选项类
class UpgradeOption:
    def __init__(self, text, index):
        self.text = text
        self.index = index
        self.rect = pygame.Rect(0, 0, 300, 60)
    
    def draw(self, screen, x, y, selected=False):
        self.rect.x = x
        self.rect.y = y
        
        # 绘制背景
        color = BOTTOM_MENU_HIGHLIGHT if selected else (50, 70, 120)
        pygame.draw.rect(screen, color, self.rect, border_radius=8)
        pygame.draw.rect(screen, UI_BORDER, self.rect, 2, border_radius=8)
        
        # 绘制文本
        text = font_medium.render(self.text, True, TEXT_COLOR)
        text_rect = text.get_rect(center=self.rect.center)
        screen.blit(text, text_rect)

# 底部菜单类 - 使用10%宽度设计
class BottomMenu:
    def __init__(self):
        self.height = HEIGHT // 4  # 底部25%的高度
        self.y_pos = HEIGHT - self.height
        self.visible = True
        self.buttons = []
        self.selected_button = 0
        self.create_buttons_with_10p_width()
    
    def create_buttons_with_10p_width(self):
        # 创建按钮 - 使用10%宽度
        button_width = WIDTH // 10  # 10%宽度
        button_height = 50
        button_margin = 10
        start_x = (WIDTH - (5 * button_width + 4 * button_margin)) // 2  # 居中
        
        # 创建5个按钮
        for i in range(5):
            btn = pygame.Rect(
                start_x + i * (button_width + button_margin),
                self.y_pos + 20,
                button_width,
                button_height
            )
            self.buttons.append(btn)
    
    def draw(self, screen):
        if not self.visible:
            return
        
        # 绘制底部菜单背景
        pygame.draw.rect(screen, BOTTOM_MENU_BG, (0, self.y_pos, WIDTH, self.height))
        pygame.draw.line(screen, UI_BORDER, (0, self.y_pos), (WIDTH, self.y_pos), 3)
        
        # 绘制标题
        title = font_large.render("游戏菜单", True, TEXT_COLOR)
        screen.blit(title, (20, self.y_pos + 10))
        
        # 绘制按钮
        button_texts = ["武器升级", "角色技能", "游戏设置", "保存游戏", "退出"]
        for i, btn in enumerate(self.buttons):
            # 按钮背景
            color = BOTTOM_MENU_HIGHLIGHT if i == self.selected_button else (60, 60, 100)
            pygame.draw.rect(screen, color, btn, border_radius=5)
            pygame.draw.rect(screen, UI_BORDER, btn, 2, border_radius=5)
            
            # 按钮文本 - 确保文本适合按钮宽度
            text = font_medium.render(button_texts[i], True, TEXT_COLOR)
            
            # 如果文本太宽，缩小字体
            if text.get_width() > btn.width - 10:
                small_font = get_font(20)
                text = small_font.render(button_texts[i], True, TEXT_COLOR)
            
            text_rect = text.get_rect(center=btn.center)
            screen.blit(text, text_rect)
        
        # 绘制提示信息
        hint = font_small.render("按TAB键显示/隐藏菜单 | 方向键选择 | 回车确认", True, TEXT_COLOR)
        screen.blit(hint, (20, self.y_pos + self.height - 30))

# 游戏类
class Game:
    def __init__(self):
        self.player = Player(WIDTH // 2, HEIGHT // 2)
        self.enemies = []
        self.xp_orbs = []
        self.projectiles = []
        self.enemy_spawn_timer = 0
        self.game_time = 0
        self.level_up_options = []
        self.showing_upgrades = False
        self.selected_upgrade = 0
        self.score = 0
        self.game_over = False
        self.bottom_menu = BottomMenu()
        self.menu_visible = False
        self.boss_spawned = False
        self.last_level_up_time = 0
    
    def spawn_enemy(self):
        # 在屏幕边缘随机位置生成敌人
        side = random.randint(0, 3)
        if side == 0:  # 上边
            x = random.randint(0, WIDTH)
            y = -20
        elif side == 1:  # 右边
            x = WIDTH + 20
            y = random.randint(0, HEIGHT)
        elif side == 2:  # 下边
            x = random.randint(0, WIDTH)
            y = HEIGHT + 20
        else:  # 左边                           
            x = -20
            y = random.randint(0, HEIGHT)
        
        # 随机选择敌人类型
        if not self.boss_spawned and self.game_time > 360:  # 1分钟后生成BOSS
            self.boss_spawned = True
            enemy_type = "boss"
        else:
            weights = [0.6, 0.35, 0.05]  # 普通、快速、坦克的生成权重
            enemy_type = random.choices(["normal", "fast", "tank"], weights=weights)[0]
            
        self.enemies.append(Enemy(x, y, enemy_type))
    
    def spawn_xp_orb(self, x, y, value=1):
        self.xp_orbs.append(XPOrb(x, y, value))
    
    def update(self, dt):
        if self.game_over:
            return
        
        self.game_time += dt
        
        # 生成敌人
        self.enemy_spawn_timer -= dt
        spawn_rate = max(0.3, 2.0 - self.game_time / 60)  # 随时间增加生成速度
        if self.enemy_spawn_timer <= 0:
            self.enemy_spawn_timer = spawn_rate
            self.spawn_enemy()
            if random.random() < 0.1:  # 30%几率生成两个敌人
                self.spawn_enemy()
        
        # 更新玩家武器
        for weapon in self.player.weapons:
            projectile = weapon.update(dt, self.player, self.enemies)
            if projectile:
                self.projectiles.append(projectile)
        
        # 更新投射物
        for proj in self.projectiles[:]:
            if proj.update():
                self.projectiles.remove(proj)
        
        # 更新敌人
        for enemy in self.enemies[:]:
            enemy.move(self.player.x, self.player.y)
            
            # 检测敌人与玩家的碰撞
            dist = math.sqrt((self.player.x - enemy.x)**2 + (self.player.y - enemy.y)**2)
            if dist < self.player.radius + enemy.radius:
                if self.player.take_damage(enemy.damage * dt):
                    if self.player.health <= 0:
                        self.game_over = True
        
        # 更新经验球
        for orb in self.xp_orbs[:]:
            # 经验球存在时间过长时消失
            if time.time() - orb.creation_time > 10:
                self.xp_orbs.remove(orb)
                continue
                
            orb.move_towards_player(self.player.x, self.player.y)
            
            # 检测经验球与玩家的碰撞
            dist = math.sqrt((self.player.x - orb.x)**2 + (self.player.y - orb.y)**2)
            if dist < self.player.radius + orb.radius:
                self.player.add_xp(orb.value)
                self.score += orb.value
                self.xp_orbs.remove(orb)
        
        # 移除死亡敌人并生成经验球
        for enemy in self.enemies[:]:
            if enemy.health <= 0:
                self.enemies.remove(enemy)
                self.spawn_xp_orb(enemy.x, enemy.y, enemy.xp_value)
                self.score += enemy.xp_value
    
    def draw(self, screen):
        # 绘制背景
        screen.fill(BACKGROUND)
        
        # 绘制网格背景
        grid_size = 40
        for x in range(0, WIDTH, grid_size):
            pygame.draw.line(screen, (40, 40, 60), (x, 0), (x, HEIGHT), 1)
        for y in range(0, HEIGHT, grid_size):
            pygame.draw.line(screen, (40, 40, 60), (0, y), (WIDTH, y), 1)
        
        # 绘制经验球
        for orb in self.xp_orbs:
            orb.draw(screen)
        
        # 绘制敌人
        for enemy in self.enemies:
            enemy.draw(screen)
        
        # 绘制投射物
        for proj in self.projectiles:
            proj.draw(screen)
        
        # 绘制玩家
        self.player.draw(screen)
        
        # 绘制UI
        self.draw_ui(screen)
        
        # 绘制升级选项
        if self.showing_upgrades:
            self.draw_upgrade_screen(screen)
        
        # 绘制底部菜单
        if self.menu_visible:
            self.bottom_menu.draw(screen)
        
        # 游戏结束画面
        if self.game_over:
            self.draw_game_over(screen)
    
    def draw_ui(self, screen):
        # 绘制顶部UI栏
        pygame.draw.rect(screen, UI_BG, (0, 0, WIDTH, 40))
        pygame.draw.line(screen, UI_BORDER, (0, 40), (WIDTH, 40), 2)
        
        # 绘制等级
        level_text = font_medium.render(f"等级: {self.player.level}", True, TEXT_COLOR)
        screen.blit(level_text, (10, 10))
        
        # 绘制经验条 - 确保经验值不会为负
        xp_percent = min(1.0, max(0, self.player.xp / self.player.xp_to_level))
        xp_bar_width = 200
        pygame.draw.rect(screen, (30, 30, 60), (WIDTH - xp_bar_width - 10, 15, xp_bar_width, 15))
        pygame.draw.rect(screen, XP_COLOR, (WIDTH - xp_bar_width - 10, 15, xp_bar_width * xp_percent, 15))
        pygame.draw.rect(screen, UI_BORDER, (WIDTH - xp_bar_width - 10, 15, xp_bar_width, 15), 2)
        
        # 显示经验值文本
        xp_text = font_small.render(f"XP: {self.player.xp}/{self.player.xp_to_level}", True, TEXT_COLOR)
        screen.blit(xp_text, (WIDTH - xp_bar_width - 10 + xp_bar_width//2 - xp_text.get_width()//2, 17))
        
        # 绘制分数
        score_text = font_medium.render(f"分数: {self.score}", True, TEXT_COLOR)
        screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, 10))
        
        # 绘制游戏时间
        minutes = int(self.game_time // 60)
        seconds = int(self.game_time % 60)
        time_text = font_medium.render(f"{minutes:02d}:{seconds:02d}", True, TEXT_COLOR)
        screen.blit(time_text, (WIDTH - 100, 10))
        
        # 绘制菜单提示
        if not self.menu_visible:
            menu_hint = font_small.render("按TAB打开菜单", True, (150, 150, 200))
            screen.blit(menu_hint, (WIDTH - menu_hint.get_width() - 10, HEIGHT - 20))
    
    def draw_upgrade_screen(self, screen):
        # 绘制半透明背景
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))
        screen.blit(overlay, (0, 0))
        
        # 绘制标题
        title = font_title.render("选择升级", True, TEXT_COLOR)
        screen.blit(title, (WIDTH // 2 - title.get_width() // 2, 80))
        
        # 绘制升级选项
        option_height = 70
        start_y = HEIGHT // 2 - (len(self.level_up_options) * option_height) // 2
        
        for i, option in enumerate(self.level_up_options):
            # 确保选项文本不会太长
            if len(option.text) > 30:
                option.text = option.text[:27] + "..."
            option.draw(screen, WIDTH // 2 - 150, start_y + i * option_height, i == self.selected_upgrade)
        
        # 绘制提示
        hint = font_small.render("使用方向键选择，按回车确认", True, (200, 200, 255))
        screen.blit(hint, (WIDTH // 2 - hint.get_width() // 2, HEIGHT - 50))
    
    def draw_game_over(self, screen):
        # 绘制半透明背景
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 200))
        screen.blit(overlay, (0, 0))
        
        # 绘制游戏结束文本
        game_over_text = font_title.render("游戏结束!", True, (220, 50, 50))
        screen.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2, HEIGHT // 2 - 100))
        
        # 绘制分数
        score_text = font_large.render(f"最终分数: {self.score}", True, TEXT_COLOR)
        screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2 - 30))
        
        # 绘制游戏时间
        minutes = int(self.game_time // 60)
        seconds = int(self.game_time % 60)
        time_text = font_large.render(f"生存时间: {minutes:02d}:{seconds:02d}", True, TEXT_COLOR)
        screen.blit(time_text, (WIDTH // 2 - time_text.get_width() // 2, HEIGHT // 2 + 30))
        
        # 绘制重新开始提示
        restart_text = font_medium.render("按R键重新开始", True, TEXT_COLOR)
        screen.blit(restart_text, (WIDTH // 2 - restart_text.get_width() // 2, HEIGHT // 2 + 100))
        
        # 绘制退出提示
        quit_text = font_medium.render("按ESC键退出", True, TEXT_COLOR)
        screen.blit(quit_text, (WIDTH // 2 - quit_text.get_width() // 2, HEIGHT // 2 + 140))
    
    def generate_upgrade_options(self):
        self.level_up_options = []
        
        # 武器升级选项
        for weapon in self.player.weapons:
            if weapon.level < weapon.max_level:
                self.level_up_options.append(
                    UpgradeOption(f"升级 {weapon.name} (等级 {weapon.level}→{weapon.level+1})", 
                                 len(self.level_up_options))
                )
        
        # 新武器选项
        if len(self.player.weapons) < 3:
            new_weapons = [
                ("火焰法杖", 0.9, 8, 180),
                ("闪电链", 1.5, 15, 220),
                ("神圣之光", 2.0, 25, 250)
            ]
            for name, cd, dmg, rng in new_weapons:
                self.level_up_options.append(
                    UpgradeOption(f"新武器: {name}", len(self.level_up_options))
                )
        
        # 被动升级选项
        passives = [
            ("最大生命值", "增加20点生命值"),
            ("移动速度", "增加10%移动速度"),
            ("经验获取", "增加25%经验获取")
        ]
        for name, desc in passives:
            self.level_up_options.append(
                UpgradeOption(f"{name}: {desc}", len(self.level_up_options))
            )
        
        # 随机排序选项
        random.shuffle(self.level_up_options)
        self.level_up_options = self.level_up_options[:3]  # 只显示3个选项
    
    def apply_upgrade(self, index):
        option = self.level_up_options[index]
        
        # 应用升级
        if "升级" in option.text:
            for weapon in self.player.weapons:
                if weapon.name in option.text:
                    weapon.upgrade()
                    break
        elif "新武器" in option.text:
            # 添加新武器
            if "火焰法杖" in option.text:
                self.player.weapons.append(Weapon("火焰法杖", 0.9, 8, 180))
            elif "闪电链" in option.text:
                self.player.weapons.append(Weapon("闪电链", 1.5, 15, 220))
            elif "神圣之光" in option.text:
                self.player.weapons.append(Weapon("神圣之光", 2.0, 25, 250))
        elif "最大生命值" in option.text:
            self.player.max_health += 20
            self.player.health = self.player.max_health
        elif "移动速度" in option.text:
            self.player.speed *= 1.1
        elif "经验获取" in option.text:
            self.player.xp_multiplier *= 1.25

# 主游戏循环
def main():
    clock = pygame.time.Clock()
    game = Game()
    running = True
    
    while running:
        dt = clock.tick(60) / 1000.0  # 转换为秒
        
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                
                if event.key == pygame.K_r and game.game_over:
                    # 重新开始游戏
                    game = Game()
                
                if game.showing_upgrades:
                    if event.key == pygame.K_UP:
                        game.selected_upgrade = (game.selected_upgrade - 1) % len(game.level_up_options)
                    elif event.key == pygame.K_DOWN:
                        game.selected_upgrade = (game.selected_upgrade + 1) % len(game.level_up_options)
                    elif event.key == pygame.K_RETURN:
                        game.apply_upgrade(game.selected_upgrade)
                        game.showing_upgrades = False
                
                # 底部菜单控制
                if game.menu_visible:
                    if event.key == pygame.K_TAB:
                        game.menu_visible = False
                    elif event.key == pygame.K_LEFT:
                        game.bottom_menu.selected_button = (game.bottom_menu.selected_button - 1) % len(game.bottom_menu.buttons)
                    elif event.key == pygame.K_RIGHT:
                        game.bottom_menu.selected_button = (game.bottom_menu.selected_button + 1) % len(game.bottom_menu.buttons)
                    elif event.key == pygame.K_RETURN:
                        # 菜单选项功能
                        if game.bottom_menu.selected_button == 4:  # 退出按钮
                            running = False
                else:
                    if event.key == pygame.K_TAB:
                        game.menu_visible = True
        
        # 玩家移动
        keys = pygame.key.get_pressed()
        dx, dy = 0, 0
        if keys[pygame.K_w] or keys[pygame.K_UP]:
            dy -= 1
        if keys[pygame.K_s] or keys[pygame.K_DOWN]:
            dy += 1
        if keys[pygame.K_a] or keys[pygame.K_LEFT]:
            dx -= 1
        if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            dx += 1
            
        # 归一化对角线移动
        if dx != 0 and dy != 0:
            dx *= 0.7071
            dy *= 0.7071
            
        game.player.move(dx, dy)
        
        # 更新游戏状态
        game.update(dt)
        
        # 检查是否需要升级 - 添加冷却时间防止连续升级
        current_time = time.time()
        if (not game.showing_upgrades and not game.game_over and not game.menu_visible and 
            game.player.xp >= game.player.xp_to_level and 
            current_time - game.last_level_up_time > 0.5):
            if game.player.level_up():
                game.generate_upgrade_options()
                game.showing_upgrades = True
                game.selected_upgrade = 0
                game.last_level_up_time = current_time
        
        # 绘制游戏
        game.draw(screen)
        pygame.display.flip()
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()
